// 格式化文件大小
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
export const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取文件类型图标
export const getFileIcon = (fileName: string, type: string): string => {
  if (type === 'folder') return 'folder'
  
  const ext = fileName.split('.').pop()?.toLowerCase() || ''
  
  const iconMap: Record<string, string> = {
    // 图片
    'jpg': 'image', 'jpeg': 'image', 'png': 'image', 'gif': 'image', 
    'bmp': 'image', 'svg': 'image', 'webp': 'image', 'ico': 'image',
    // 文档
    'pdf': 'pdf', 
    'doc': 'document', 'docx': 'document', 'txt': 'document', 
    'md': 'document', 'rtf': 'document',
    // 表格
    'xls': 'spreadsheet', 'xlsx': 'spreadsheet', 'csv': 'spreadsheet',
    // 演示文稿
    'ppt': 'presentation', 'pptx': 'presentation',
    // 压缩文件
    'zip': 'archive', 'rar': 'archive', '7z': 'archive', 
    'tar': 'archive', 'gz': 'archive',
    // 音频
    'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 
    'aac': 'audio', 'm4a': 'audio', 'ogg': 'audio',
    // 视频
    'mp4': 'video', 'avi': 'video', 'mkv': 'video', 
    'mov': 'video', 'wmv': 'video', 'flv': 'video', 'webm': 'video',
    // 代码
    'js': 'code', 'ts': 'code', 'html': 'code', 'css': 'code', 
    'json': 'code', 'xml': 'code', 'py': 'code', 'java': 'code', 
    'cpp': 'code', 'c': 'code', 'cs': 'code', 'php': 'code', 'go': 'code',
    'vue': 'code', 'jsx': 'code', 'tsx': 'code', 'scss': 'code', 'less': 'code',
    // 可执行文件
    'exe': 'executable', 'msi': 'executable', 'app': 'executable', 
    'deb': 'executable', 'rpm': 'executable'
  }
  
  return iconMap[ext] || 'file'
}

// 复制到剪贴板
export const copyToClipboard = async (text: string): Promise<boolean> => {
  try {
    await navigator.clipboard.writeText(text)
    return true
  } catch (err) {
    // 备用方法
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      document.body.removeChild(textArea)
      return true
    } catch (error) {
      document.body.removeChild(textArea)
      return false
    }
  }
}

// 获取文件扩展名
export const getFileExtension = (fileName: string): string => {
  return fileName.split('.').pop()?.toLowerCase() || ''
}

// 判断是否为图片文件
export const isImageFile = (fileName: string): boolean => {
  const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp']
  return imageExts.includes(getFileExtension(fileName))
}

// 判断是否为视频文件
export const isVideoFile = (fileName: string): boolean => {
  const videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm']
  return videoExts.includes(getFileExtension(fileName))
}

// 判断是否为音频文件
export const isAudioFile = (fileName: string): boolean => {
  const audioExts = ['mp3', 'wav', 'flac', 'aac', 'm4a', 'ogg']
  return audioExts.includes(getFileExtension(fileName))
}

// 生成唯一ID
export const generateId = (): string => {
  return Math.random().toString(36).substr(2, 9)
}

// 验证文件名
export const isValidFileName = (name: string): boolean => {
  // 不能包含特殊字符
  const invalidChars = /[<>:"/\\|?*]/
  return !invalidChars.test(name) && name.trim().length > 0
}

// 获取安全的文件名
export const getSafeFileName = (name: string): string => {
  return name.replace(/[<>:"/\\|?*]/g, '_').trim()
}

// XSS防护 - HTML转义
export const escapeHtml = (text: string): string => {
  if (!text) return ''
  
  const htmlEscapes: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;',
    '`': '&#x60;',
    '=': '&#x3D;'
  }
  
  return text.replace(/[&<>"'`=\/]/g, (match) => htmlEscapes[match])
}

// 安全显示文件名 - 针对文件名的特殊XSS防护
export const sanitizeDisplayName = (fileName: string): string => {
  if (!fileName) return '未知文件'
  
  // 首先进行HTML转义
  let safeName = escapeHtml(fileName)
  
  // 移除或转义可能的脚本标签和事件处理
  safeName = safeName.replace(/javascript:/gi, '')
  safeName = safeName.replace(/on\w+\s*=/gi, '')
  safeName = safeName.replace(/script/gi, '')
  safeName = safeName.replace(/iframe/gi, '')
  safeName = safeName.replace(/object/gi, '')
  safeName = safeName.replace(/embed/gi, '')
  
  // 限制长度，防止过长的文件名影响UI
  if (safeName.length > 255) {
    safeName = safeName.substring(0, 252) + '...'
  }
  
  return safeName
}

// 安全显示文本内容 - 通用文本XSS防护
export const sanitizeText = (text: string): string => {
  if (!text) return ''
  
  // HTML转义
  let safeText = escapeHtml(text)
  
  // 移除潜在的危险内容
  safeText = safeText.replace(/javascript:/gi, '')
  safeText = safeText.replace(/data:/gi, '')
  safeText = safeText.replace(/vbscript:/gi, '')
  
  return safeText
}

// 验证并清理用户输入 - 用于表单输入
export const validateAndCleanInput = (input: string, maxLength: number = 255): string => {
  if (!input) return ''
  
  // 移除前后空白
  let cleaned = input.trim()
  
  // 长度限制
  if (cleaned.length > maxLength) {
    cleaned = cleaned.substring(0, maxLength)
  }
  
  // 移除危险字符
  cleaned = cleaned.replace(/[<>]/g, '')
  cleaned = cleaned.replace(/javascript:/gi, '')
  cleaned = cleaned.replace(/on\w+\s*=/gi, '')
  
  return cleaned
}

// 检查字符串是否包含潜在XSS
export const containsPotentialXSS = (text: string): boolean => {
  const xssPatterns = [
    /<script/i,
    /javascript:/i,
    /on\w+\s*=/i,
    /<iframe/i,
    /<object/i,
    /<embed/i,
    /vbscript:/i,
    /data:text\/html/i
  ]
  
  return xssPatterns.some(pattern => pattern.test(text))
} 